package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constrant.ProductConst;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttrVo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);

        // 基本属性才有分组
        if (attr.getAttrType() == ProductConst.AttrEnum.ARRE_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            this.relationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils baseList(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type",
                        StringUtils.equals("base", attrType)? ProductConst.AttrEnum.ARRE_TYPE_BASE.getCode() :
                        ProductConst.AttrEnum.ARRE_TYPE_SALE.getCode());
        if (Objects.nonNull(catelogId) && catelogId != 0L) {
            wrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            // WHERE (attr_type = 0 AND attr_id = 1 OR attr_name LIKE '%1%') LIMIT 0,10
            // wrapper.eq("attr_id", key).or().like("attr_name", key);
            // WHERE (attr_type = ? AND ( (attr_id = ? OR attr_name LIKE ?) )) LIMIT ?,?
            wrapper.and(QueryWrapper -> QueryWrapper.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> list = (List<AttrEntity>) pageUtils.getList();
        List<AttrRespVo> collect = list.parallelStream().map(item -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(item, attrRespVo);

            // 分类信息
            Long itemCatelogId = item.getCatelogId();
            if (Objects.nonNull(itemCatelogId)) {
                CategoryEntity categoryEntity = categoryDao.selectById(itemCatelogId);
                attrRespVo.setCatelogName(categoryEntity.getName());
            }

            // 分组信息
            if (item.getAttrType() == ProductConst.AttrEnum.ARRE_TYPE_BASE.getCode()) {
                Long attrId = item.getAttrId();
                if (Objects.nonNull(attrId)) {
                    AttrAttrgroupRelationEntity relationEntity = this.relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
                    if (Objects.nonNull(relationEntity) && Objects.nonNull(relationEntity.getAttrGroupId())) {
                        AttrGroupEntity attrGroupEntity = this.attrGroupDao.selectById(relationEntity.getAttrGroupId());
                        if (Objects.nonNull(attrGroupEntity)) {
                            attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                        }
                    }
                }
            }

            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(collect);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttr(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity byId = this.getById(attrId);
        BeanUtils.copyProperties(byId, attrRespVo);

        // 查询规格参数时查询分组信息
        if (byId.getAttrType() == ProductConst.AttrEnum.ARRE_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = this.relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (Objects.nonNull(relationEntity)) {
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = this.attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (Objects.nonNull(attrGroupEntity)) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 分类信息
        Long[] catelogPath = this.categoryService.findCatelogPath(byId.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = this.categoryDao.selectById(byId.getCatelogId());
        if (Objects.nonNull(categoryEntity)) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        // 基本属性时在更新分组信息
        if (attrEntity.getAttrType() == ProductConst.AttrEnum.ARRE_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            QueryWrapper<AttrAttrgroupRelationEntity> attr_id = new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId());
            Integer integer = this.relationDao.selectCount(attr_id);
            if (integer > 0) {
                this.relationDao.update(relationEntity, attr_id);
            } else {
                this.relationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getAttrRelation(Long attrgroupId) {
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_group_id", attrgroupId);
        List<AttrAttrgroupRelationEntity> relationEntityList = this.relationDao.selectList(wrapper);
        List<Long> attrIds = relationEntityList.parallelStream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(attrIds)) {
            return Collections.EMPTY_LIST;
        }
        List<AttrEntity> attrEntities = this.attrDao.selectBatchIds(attrIds);
        return attrEntities;
    }

    @Override
    public PageUtils getNotRelatedAttr(Map<String, Object> params, Long attrgroupId) {
        //根据属性分组查商品分类
        AttrGroupEntity attrGroupEntity = this.attrGroupDao.selectById(attrgroupId);
        //商品分类下所有规格属性
        List<AttrEntity> attrEntityList = this.attrDao.selectList(new QueryWrapper<AttrEntity>().eq("catelog_id", attrGroupEntity.getCatelogId()));
        List<Long> allAttrIds = attrEntityList.parallelStream().map(AttrEntity::getAttrId).collect(Collectors.toList());
        //商品分类下所有的属性分组
        List<AttrGroupEntity> attrGroupEntityList = this.attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", attrGroupEntity.getCatelogId()));
        List<Long> allAttrGroupIds = attrGroupEntityList.parallelStream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        //商品分类下已关联分组的规格属性
        QueryWrapper<AttrAttrgroupRelationEntity> relationWrapper = new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_id", allAttrIds).in("attr_group_id", allAttrGroupIds);
        List<AttrAttrgroupRelationEntity> relationEntityList = this.relationDao.selectList(relationWrapper);
        List<Long> relatedAttrIds = relationEntityList.parallelStream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        //未关联的
        allAttrIds.removeAll(relatedAttrIds);
        //查询规格属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", ProductConst.AttrEnum.ARRE_TYPE_BASE.getCode());
        String key = (String)params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        if (!CollectionUtils.isEmpty(allAttrIds)) {
            wrapper.in("attr_id", allAttrIds);
        }
        //分页查询
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

}